package com.jiexin.service;

import com.google.common.base.Preconditions;
import com.jiexin.beans.PageQuery;
import com.jiexin.beans.PageResult;
import com.jiexin.common.RequestHolder;
import com.jiexin.dao.SysAclMapper;
import com.jiexin.exception.ParamException;
import com.jiexin.model.SysAcl;
import com.jiexin.model.SysAclModule;
import com.jiexin.model.SysUser;
import com.jiexin.param.AclParam;
import com.jiexin.util.BeanValidator;
import com.jiexin.util.IpUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.management.relation.RelationType;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author: Jay_Liu
 * @Description:
 * @Date: Created in 10:54 2018/4/19 0019
 * @Modified By:
 */
@Service
public class SysAclService {

    @Resource
    SysAclMapper sysAclMapper;

    @Resource
    private SysLogService sysLogService;

    public void save(AclParam param) {
        //检查参数各字段是否合法
        BeanValidator.check(param);
        //判断是否存在相同权限名称
        if (checkIsExist(param.getAclModuleId(),  param.getName(), param.getId())) {
            throw new ParamException("同一权限模块下不能存在相同的权限");
        }
        //新的权限对象
        SysAcl acl = SysAcl.builder().name(param.getName()).aclModuleId(param.getAclModuleId())
                .url(param.getUrl()).type(param.getType()).status(param.getStatus()).seq(param.getSeq()).remark(param.getRemark()).build();
        acl.setCode(generateCode());
        acl.setOperator(RequestHolder.getCurrentUser().getUsername());
        acl.setOperateTime(new Date());
        acl.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysAclMapper.insertSelective(acl);
        sysLogService.saveAclLog(null, acl);
    }

    public void update(AclParam param) {
        //检查参数各字段是否合法
        BeanValidator.check(param);
        //判断是否存在相同权限名称
        if (checkIsExist(param.getAclModuleId(), param.getName(), param.getId())) {
            throw new ParamException("同一权限模块下不能存在相同的权限");
        }
        //不可移动到权限模块本身 TODO：
        //获取原先权限信息
        SysAcl before = sysAclMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before, "待更新的权限点不存在");
        //日志记录原先的权限信息 TODO：
        //新的权限信息
        SysAcl after = SysAcl.builder().id(param.getId()).name(param.getName()).aclModuleId(param.getAclModuleId())
                .url(param.getUrl()).type(param.getType()).status(param.getStatus()).seq(param.getSeq()).remark(param.getRemark()).build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateTime(new Date());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysAclMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveAclLog(before, after);
    }

    /**
     * 使用时间戳+随机数生成权限码
     * @return 权限码
     */
    private String generateCode() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(new Date()) + "_" + (int)(Math.random() * 100);
    }

    private boolean checkIsExist(Integer aclModuleId, String name, Integer id) {
        return sysAclMapper.countByNameAndAclModuleId(aclModuleId, name, id) >0;
    }

    /**
     * 获取对应权限模块下的分页权限点
     * @param aclModuleId 权限模块ID
     * @param page 分页请求参数
     * @return 分页权限点
     */
    public PageResult<SysAcl> getPageByAclModuleId(int aclModuleId, PageQuery page) {
        //检查分页参数
        BeanValidator.check(page);
        //获取当前权限模块ID下的权限数量
        int count = sysAclMapper.countByaclModuleId(aclModuleId);
        if (count > 0) {
            List<SysAcl> aclList = sysAclMapper.getPageByAclModuleId(aclModuleId, page);
            return PageResult.<SysAcl>builder().data(aclList).total(count).build();
        }
        return PageResult.<SysAcl>builder().build();
    }
}
